//
//  MeViewController.m
//  LogisticsFollow
//
//  Created by JustFei on 2016/12/17.
//  Copyright © 2016年 manridy. All rights reserved.
//

#import "MeViewController.h"
#import "ResetPwdViewController.h"
#import "AFNetworking.h"
#import "UserInfoModel.h"
#import "LoginViewController.h"
#import "FMDBTool.h"

@interface MeViewController () < UITableViewDelegate , UITableViewDataSource >

@property (weak, nonatomic) IBOutlet UIImageView *headImageView;
@property (weak, nonatomic) IBOutlet UILabel *userNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *carTypeLabel;
@property (weak, nonatomic) IBOutlet UILabel *carNumLabel;
@property (weak, nonatomic) IBOutlet UIView *sendCountView;
@property (weak, nonatomic) IBOutlet UILabel *sendCountLabel;
@property (weak, nonatomic) IBOutlet UIView *mileageView;
@property (weak, nonatomic) IBOutlet UILabel *mileageLabel;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *logoutButton;
@property (nonatomic ,strong) NSArray *imageArr;
@property (nonatomic ,strong) NSArray *nameArr;
@property (nonatomic ,strong) FMDBTool *myFmdbTool;

@end

@implementation MeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self getDataFromDB];
    [self createUI];
    [self getData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [[self.navigationController.navigationBar subviews].firstObject setAlpha:0];
    self.navigationController.navigationBar.barTintColor = kClearColor;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)getDataFromDB
{
    NSArray *userArr = [self.myFmdbTool queryUserInfoModel:nil];
    UserInfoResultModel *model = userArr.firstObject;
    self.userNameLabel.text = [NSString stringWithFormat:@"%@欢迎您",model.name];
    self.carTypeLabel.text = [NSString stringWithFormat:@"车辆：%@",model.car];
    self.carNumLabel.text = [NSString stringWithFormat:@"车牌号：%@",model.carNo];
    self.sendCountLabel.text = model.deliveryCount.stringValue;
    self.mileageLabel.text = model.totalMileage.stringValue;
}

- (void)createUI
{
    self.navigationItem.title = @"个人中心";
    self.navigationController.navigationBar.tintColor = kWhiteColor;
    
    self.sendCountView.clipsToBounds = YES;
    self.sendCountView.layer.borderWidth = 1;
    self.sendCountView.layer.borderColor = kWhiteColor.CGColor;
    self.mileageView.clipsToBounds = YES;
    self.mileageView.layer.borderWidth = 1;
    self.mileageView.layer.borderColor = kWhiteColor.CGColor;
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationItem.backBarButtonItem = backItem;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc] init];
}

- (void)getData
{
//    [dispatch_async(dispatch_get_global_queue(1, 1), ^{
        // 启动系统风火轮
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
        
        //服务器给的域名
        NSString *domainStr = kUserInfoPort;
        
        //假如需要提交给服务器的参数是key＝1,class_id=100
        //创建一个可变字典
        NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
        //往字典里面添加需要提交的参数
        NSString *guid = [[NSUserDefaults standardUserDefaults] objectForKey:@"guid"];
        [parametersDic setObject:guid forKey:@"guid"];
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        //以post的形式提交，POST的参数就是上面的域名，parameters的参数是一个字典类型，将上面的字典作为它的参数
        [manager POST:domainStr parameters:parametersDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            // 隐藏系统风火轮
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            
            //json解析
            NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            //转成jsonModel
            UserInfoModel *model = [[UserInfoModel alloc] initWithDictionary:resultDic error:nil ];
            NSLog(@"isSuccess = %d\nmsg = %@\nresult = %@",model.isSuccess ,model.msg ,model.result);
            if (model.isSuccess) {
                UserInfoResultModel *resultModel = model.result[0];
                [self doSuccessGetUserData:resultModel];
            }else {
//                [self doFailGetUserData];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            // 解析失败隐藏系统风火轮(可以打印error.userInfo查看错误信息)
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
//            [self doFailGetUserData];
        }];
//    }];
}

#pragma mark - UITableViewDelegate && UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    }
    cell.imageView.image = [UIImage imageNamed:self.imageArr[indexPath.row]];
    cell.textLabel.text = self.nameArr[indexPath.row];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.row) {
        case 0:
        {
            ResetPwdViewController *vc = [[ResetPwdViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - Action
- (IBAction)logoutAction:(UIButton *)sender
{
    UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"提示" message:@"确认退出？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAc = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"logined"];
        [self.myFmdbTool deleteUserInfoModel:4];
        LoginViewController *loginVc = [[LoginViewController alloc] init];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self presentViewController:loginVc animated:YES completion:nil];
        });
    }];
    UIAlertAction *cancelAc = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
    [vc addAction:cancelAc];
    [vc addAction:okAc];
    
    [self presentViewController:vc animated:YES completion:nil];
    
}

- (NSArray *)imageArr
{
    if (!_imageArr) {
        _imageArr = @[@"resetPwd",@"protocol"];
    }
    
    return _imageArr;
}

- (NSArray *)nameArr
{
    if (!_nameArr) {
        _nameArr = @[@"修改密码",@"《司机服务协议》"];
    }
    
    return _nameArr;
}

- (void)doSuccessGetUserData:(UserInfoResultModel *)model
{
    [self.myFmdbTool insertUserInfoModel:model];
    self.userNameLabel.text = [NSString stringWithFormat:@"%@欢迎您",model.name];
    self.carTypeLabel.text = [NSString stringWithFormat:@"车辆：%@",model.car];
    self.carNumLabel.text = [NSString stringWithFormat:@"车牌号：%@",model.carNo];
    self.sendCountLabel.text = model.deliveryCount.stringValue;
    self.mileageLabel.text = model.totalMileage.stringValue;
}

#pragma mark - 懒加载
- (FMDBTool *)myFmdbTool
{
    if (!_myFmdbTool) {
        NSString *guid = [[NSUserDefaults standardUserDefaults] objectForKey:@"guid"];
        _myFmdbTool = [[FMDBTool alloc] initWithPath:guid];
    }
    
    return _myFmdbTool;
}

@end
